package nju.software.tagmanager.interceptor;

import com.alibaba.fastjson.JSON;
import nju.software.tagmanager.common.constant.JwtClaimsConstant;
import nju.software.tagmanager.common.context.BaseContext;
import nju.software.tagmanager.common.exception.TokenExpiredException;
import nju.software.tagmanager.common.properties.JwtProperties;
import nju.software.tagmanager.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import nju.software.tagmanager.common.utils.RedisUtil;
import nju.software.tagmanager.pojo.entity.User;
import nju.software.tagmanager.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;

import static nju.software.tagmanager.common.constant.RedisKeyPrefixConstant.REDIS_USER_KEY_PREFIX;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private UserService userService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * @author: raychou
     * @params: [request, response, handler]
     * @paramTypes: [javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object]
     * @return: boolean
     * @date: 2023/9/1 16:11
     * @description: 校验jwt
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            Integer userId = Integer.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户id：{}", userId);


            //TODO 从Redis读
            String redisKey = REDIS_USER_KEY_PREFIX + userId;
            User user = JSON.parseObject(JSON.toJSONString(redisUtil.hget(redisKey, "user")), User.class);
            List<String> roles = (List<String>) redisUtil.hget(redisKey, "roles");

            BaseContext.setCurrentUserId(userId);
            BaseContext.setCurrentUser(user);
            BaseContext.setCurrentRoles(roles);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //通过抛异常，让全局异常处理器捕获，给前段发错误消息，而不是返回false
            throw new TokenExpiredException();
        }
    }
}
